/**
 * Created by wanthering on 2017/9/7.
 */


'use strict'

var qiniu = {
  upload:"https://up.qbox.me",
  bucket:"https://oimcnea2a.qnssl.com/",
  noBucket:'oimcnea2a.qnssl.com/',
  bucketName:'rijinop-upload-image'
}

function uploadToQiniu(file,token,key,cb){
  var xhr = new XMLHttpRequest();
  xhr.open('POST', qiniu.upload, true);
  var formData, startDate;
  formData = new FormData();
  if (key !== null && key !== undefined) formData.append('key', key);
  formData.append('token', token);
  formData.append('file', file);
  var taking;
  xhr.upload.addEventListener("progress", function(evt) {
    if (evt.lengthComputable) {
      var nowDate = new Date().getTime();
      taking = nowDate - startDate;
      var x = (evt.loaded) / 1024;
      var y = taking / 1000;
      var uploadSpeed = (x / y);
      var formatSpeed;
      if (uploadSpeed > 1024) {
        formatSpeed = (uploadSpeed / 1024).toFixed(2) + "Mb\/s";
      } else {
        formatSpeed = uploadSpeed.toFixed(2) + "Kb\/s";
      }
      let percentComplete = Math.round(evt.loaded * 100 / evt.total);
      console && console.log(percentComplete, ",", formatSpeed);
    }
  }, false);
  xhr.onreadystatechange = handler;

  function handler(response){

    if (this.readyState !== 4) {
      return;
    }
    if (xhr.status === 200) {
      var blkRet = JSON.parse(xhr.responseText);
      cb(blkRet)
    } else {
      throw(new Error(xhr.statusText));
    }
  }
  startDate = new Date().getTime();
  xhr.send(formData);
}


$(function(){
  $('[data-toggle="datepicker"]').datepicker(
    {date: addDate(2),
      autoPick:true
    }
  );

  function addDate(days) {
    if (days === undefined || days === '') {
      days = 1;
    }
    var date = new Date();
    date.setDate(date.getDate() + days);
    var month = date.getMonth() + 1;
    var year = date.getYear();
    var day = date.getDate();
    var newDate = new Date(year,month,day)
    return date
  }


  var  $gift = $('#giftList'),
    $giftUrl = $('#giftUrl'),   ratio =  1,
    thumbnailWidth = 100 * ratio,
    thumbnailHeight = 100 * ratio;

  var $btn = $('<div class="filePanel"><span></span></div>');

  var giftLoader = WebUploader.create({
    pick: {
      id: '#giftPicker'
    },
    swf: '../utils/Uploader.swf',
    chunked: false,
    chunkSize: 512 * 1024,
    // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
    disableGlobalDnd: true,
    fileNumLimit: 1,
    fileSizeLimit: 200 * 1024 * 1024,    // 200 M
    fileSingleSizeLimit: 50 * 1024 * 1024    // 50 M
  });

  giftLoader.on('filesQueued', function(file) {
    uploadQiniuFile(file,$gift,$giftUrl,this)
  });

  function uploadQiniuFile(file,thumb,value,handle){
    var uploadFile = file[0].source.source
    console.log(uploadFile)
    var fileSeg = file[0].name.split('.')
    var key = 'audio_face_' +(new Date()).valueOf() + '.' + fileSeg[1];
    console.log(key)
    $.ajax('https://biz-op.rijin.com/api/port/getQiniuToken',{
      method: 'POST',
      type: 'json',
      data: {
        key: key
      },
      success: function(d){
        if(d && d.success){
          console.log('token:',d.token)
          var token = d.token
          uploadToQiniu(uploadFile,token,key,function(bkt){
            previewFile(bkt.key,file[0],thumb,value,handle)
          })
        }else{
          console.log('上传发生错误')
        }
      }
    })
  }


  var readGiftUrl  = $('#giftUrl').val();
  if(readGiftUrl && readGiftUrl!=='##invalid##'){
    var $readGiftBtn = $('<div class="filePanel"><span></span></div>')
    var $readGiftImg = $('<img src="'+readGiftUrl+'" width="'+thumbnailWidth+'" height="'+thumbnailHeight+'">')
    $gift.append($readGiftBtn).append($readGiftImg)

    $readGiftBtn.on('click',function(){
      $gift.empty()
      $('#giftUrl').val('##invalid##')
    })
  }


  function previewFile(key,file,thumb,value,handle){

    var $btn = $('<div class="filePanel"><span></span></div>')
    handle.makeThumb(file,function(err,src){
      if(err){
        console.log(err)
      }
      var $img = $('<img src="'+src+'">')
      thumb.append($img).append($btn)
      //  进行拼接生成缩略图
    },thumbnailWidth,thumbnailHeight)

    var imageUrl = qiniu.bucket+key
    value.val(imageUrl)



    $btn.on('click',function(){
      handle.removeFile(file)
      thumb.empty()
      value.val('##invalid##')
    })
  }

})